package center

import (
	"fmt"
	"log"
	//"math/rand"
)

//购买物品
func p0021(p *Packet, coni *Conninfo) {
	user_id := byteToInt32(p.data[0:4])
	prop_id := byteToInt32(p.data[4:8])
	money_type := p.data[8]
	user_info = get_user_info(user_id)
	if user_info == nil {
		log.Print("user not found!")
		return
	}
	user_info.rwlock_user.Lock()
	defer user_info.rwlock_user.Unlock()
	prop_data := prop_config_map[prop_id]
	if prop_data == nil {
		fmt.Println("prop not found!")
		return
	}
	if money_type == 0 {
		if user_info.gold >= prop_data.price_gold {
			user_info.gold -= prop_data.price_gold
			if insert_prop_to_user(user_info, prop_data) == false {
				fmt.Println("insert into bag error!")
				return
			}
			result, err := dbcenter.Change("update user_info set gold=? where user_id=?", prop_data.price_gold, user_id)
			if err != nil {
				fmt.Println("update user_info error!")
				return
			}
			if result == nil {
				fmt.Println("update user_info error!")
				return
			}
		}
	} else if money_type == 1 {
		if user_info.silver >= prop_data.price_silver {
			user_info.silver -= prop_data.price_silver
			if insert_prop_to_user(user_info, prop_data) == false {
				fmt.Println("insert into bag error!")
				return
			}
			result, err := dbcenter.Change("update user_info set silver=? where user_id=?", prop_data.price_silver, user_id)
			if err != nil {
				fmt.Println("update user_info error!")
				return
			}
			if result == nil {
				fmt.Println("update user_info error!")
				return
			}
		}
	}
	p.data = make([]byte, 0)
	p.data = append(p.data, []byte{255}...)
	p.data_len = 1
	p.send(coni)
}
func insert_prop_to_user(user_info *User_info, prop_data *Prop_data) bool {

	var need_insert bool = true
	if prop_data.can_overly == 1 {
		bag_list := user_info.get_bag_list()
		for _, val := range bag_list {
			if val.prop_id == prop_data.prop_id {
				result, err := dbcenter.Change("update bag_things set prop_num=prop_num+? where user_id=?", 1, user_info.user_id)
				if err != nil {
					fmt.Println("update bag error!")
					return false
				}
				if result == nil {
					fmt.Println("update bag error!")
					return false
				}
				val.prop_num += 1
				need_insert = false
				break
			}
		}
	}
	if need_insert == true {
		result, err := dbcenter.Change("insert into bag_things set user_id=?,prop_id=?", user_info.user_id, prop_data.prop_id)
		if err != nil {
			fmt.Println("insert into bag error!")
			return false
		}
		if result == nil {
			fmt.Println("insert into bag error!")
			return false
		}
		bag_thing := new(Bag_thing)
		bag_thing_id, err := result.LastInsertId()
		bag_thing.bag_thing_id = int32(bag_thing_id)
		bag_thing.prop_id = prop_data.prop_id
		bag_thing.user_id = user_info.user_id
		user_info.get_bag_list()[bag_thing.bag_thing_id] = bag_thing
	}
	return true
}
